<template>
  <div class="download-con table-gl-w">
    <div class="search-w">
      <FilterTable :filterItem="filterItem" :isReset="true" @search="searchByVal" />
    </div>
    <div class="table-gl-con">
      <TableWrap style="flex: 1" @refresh="getList">
        <template #headerLeft>
          <a-space>
            <div>已选中 {{ ids.length }} 条</div>
            <a-button class="gray-outline" @click="downloadMul">打包下载</a-button>
            <a-button class="gray-outline ml10" @click="del('mul')">批量删除</a-button>
          </a-space>
        </template>
        <template #tableBody>
          <a-table size="mini" class="table-two-line" v-model:selected-keys="ids" :data="dataList" @sorter-change="sortChange" :row-selection="{ type: 'checkbox', showCheckedAll: true, width: 40 }" row-key="id" :loading="loading" :pagination="false" :scroll="{ y: '100%' }">
            <template #columns>
              <a-table-column title="序号" #cell="{ record, rowIndex }" :width="40">
                {{ rowIndex + 1 }}
              </a-table-column>
              <a-table-column title="文件名称" #cell="{ record, rowIndex }" :width="120">
                {{ record.fileName }}
              </a-table-column>
              <a-table-column title="导出位置" #cell="{ record, rowIndex }" :width="120">
                {{ record.fromLocation }}
              </a-table-column>
              <a-table-column title="请求编号" #cell="{ record, rowIndex }" :width="120">
                {{ record.requestId }}
              </a-table-column>
              <a-table-column title="请求时间" #cell="{ record, rowIndex }" :width="140" :sortable="{ sortDirections: ['ascend', 'descend'] }" data-index="startDate">
                {{ $setTime(record.gmtCreate) }}
              </a-table-column>
              <a-table-column title="完成时间" #cell="{ record, rowIndex }" :width="120">
                {{ $setTime(record.gmtFinished) }}
              </a-table-column>
              <a-table-column title="请求人" #cell="{ record, rowIndex }" :width="120">
                {{ record.createUname }}
              </a-table-column>
              <a-table-column title="状态" #cell="{ record, rowIndex }" :width="80">
                <a-tag v-if="record.status == 'HANDING'" color="#ffedca" style="color: #f69a6e">处理中</a-tag>
                <a-tag v-if="record.status == 'FINISH'" color="#ffedca" style="color: #809dea"> 已完成</a-tag>
                <a-tag v-if="record.status == 'ERROR'" color="#ffedca" style="color: #e00053">
                  <template #icon>
                    <icon-info-circle style="color: red" />
                  </template>
                  <span>处理失败</span>
                </a-tag>
              </a-table-column>
              <a-table-column title="已下载" #cell="{ record, rowIndex }" :width="80">
                {{ record.downloadNum }}
              </a-table-column>
              <a-table-column title="操作" #cell="{ record, rowIndex }" :width="60">
                <a-button type="text" class="mr10" v-if="record.status == 'FINISH'" @click="download(record)">下载</a-button>
                <a-button type="text" class="mr10" style="color: red" v-if="['FINISH', 'ERROR'].includes(record.status)" @click="del('simgle', record)">删除</a-button>
                <a-button type="text" class="mr10" style="color: #aaaaaa" v-if="record.status == 'HANDING'">等待处理...</a-button>
              </a-table-column>
            </template>
          </a-table>
        </template>
      </TableWrap>
      <div class="pagination-footer">
        <a-pagination size="mini" :page-size-options="[20, 50, 100, 200, 500]" show-total show-page-size :total="pageNation.total" :default-page-size="pageNation.pageSize" :current="pageNation.pageNum" style="float: right" @page-size-change="sizeChange" @change="changePage" />
      </div>
    </div>
  </div>
</template>

<script lang="ts" setup>
  import FilterTable from '../../../components/TableFilter.vue'
  import TableWrap from '../../../components/TableWrap.vue'
  import { ref, onMounted } from 'vue'
  import { pageDownloadCenter, delDownloadCenter, incDownloadNum } from '@/api/system'
  import { Modal, Message } from '@arco-design/web-vue'
  import _ from 'lodash-es'
  import JSZip from 'jszip'
  import FileSaver from 'file-saver'

  const filterItem = ref([
    {
      key: 'fileName',
      label: '文件名称',
      value: ref(),
      type: 'input_search',
      width: '180',
    },
    {
      key: 'fromLocation',
      label: '导出位置',
      value: ref(),
      type: 'input_search',
      width: '180',
    },
    {
      key: 'requestId',
      label: '请求编号',
      value: ref(),
      type: 'input_search',
      width: '180',
    },
    {
      key: 'createUname',
      label: '请求人',
      value: ref(),
      type: 'input_search',
      width: '180',
    },
    {
      key: 'status',
      label: '状态',
      value: ref(),
      type: 'select',
      width: 140,
      optionItems: [
        { label: '处理中', value: 'HANDING' },
        { label: '已完成', value: 'FINISH' },
        { label: '处理失败', value: 'ERROR' },
      ],
      attrs: {
        'allow-search': true,
      },
    },
    {
      key: 'downloadNum',
      label: '已下载',
      value: ref(),
      type: 'input_search',
      width: '180',
    },
  ])
  let dataList = ref([])
  let loading = ref(false)
  let pageNation = ref({ total: 0, pageSize: 20, pageNum: 1 })
  let ids = ref([])
  let searchValue: any = ref({})

  const changePage = (val: number) => {
    pageNation.value.pageNum = val
    getList()
  }

  const sizeChange = (val: number) => {
    pageNation.value.pageNum = 1
    pageNation.value.pageSize = val
    getList()
  }
  const sortChange = (item: any, extra: any) => {
    if (extra) {
      searchValue.value.sortField = item
      searchValue.value.sortType = extra == 'ascend' ? '1' : '-1'
    } else {
      searchValue.value.sortField = ''
      searchValue.value.sortType = ''
    }
    getList()
  }
  const searchByVal = (val: any) => {
    searchValue.value = {}
    searchValue.value = val
    pageNation.value.pageNum = 1
    getList()
  }
  const getList = async () => {
    let params = {
      ...searchValue.value,
      pageNum: pageNation.value.pageNum,
      pageSize: pageNation.value.pageSize,
    }
    loading.value = true
    const res: any = await pageDownloadCenter(params)
    if (res) {
      dataList.value = res?.data?.records || []
      dataList.value.map((e: any) => {
        if (e.status == 'HANDING' || e.status == 'ERROR') e.disabled = true
        return e
      })
      pageNation.value.total = res?.data?.total || 0
    }
    loading.value = false
  }

  const download = (info: any) => {
    addNum([info.id])
    const a = document.createElement('a')
    a.href = info.fileUrl
    a.click()
    a.remove()
  }

  const addNum = async (ids: Array<string>) => {
    await incDownloadNum(ids)
  }

  const del = (type: string, info?: any) => {
    if (type == 'mul') {
      if (ids.value.length <= 0) {
        return Message.error('请选择需要删除的数据')
      }
    }
    Modal.warning({
      title: '删除',
      content: '是否删除',
      cancelText: '取消',
      okText: '确认',
      titleAlign: 'start',
      hideCancel: false,
      onOk: async () => {
        let params: Array<string> = []
        type == 'mul' ? (params = ids.value) : params.push(info.id)
        let res: any = await delDownloadCenter(params)
        if (res) {
          Message.success('删除成功')
          getList()
        }
      },
    })
  }

  const downloadMul = () => {
    if (ids.value.length == 0) return Message.error('请选择需要下载的数据')
    addNum(ids.value)
    let list: Array<string> = []
    ids.value.forEach((e) => {
      let item: any = dataList.value.find((el: any) => e == el.id)
      if (item) list.push(item.fileUrl)
    })
    downloadBtn(list, '导出文件')
  }

  const downloadBtn = (fileList: any, blogTitle: string) => {
    var zip: any = new JSZip()
    var promises: any = []
    let cache = {}
    for (let item of fileList) {
      // item.feilePath为文件链接地址
      // item.fileName为文件名称
      if (item) {
        const promise = getImgArrayBuffer(item).then((fileData) => {
          // 下载文件, 并存成ArrayBuffer对象(blob)
          let fileName = item.split('/')[item.split('/').length - 1]
          console.log(fileName)

          zip.file(fileName, fileData, { binary: true }) // 逐个添加文件
          cache[item.fileName] = fileData
        })
        promises.push(promise)
      } else {
        // feilePath地址不存在时提示
        Message.error(`附件${item.fileName}地址错误，下载失败`)
      }
    }

    Promise.all(promises)
      .then(() => {
        zip.generateAsync({ type: 'blob' }).then((content: any) => {
          // 生成二进制流
          FileSaver.saveAs(content, blogTitle) // 利用file-saver保存文件  blogTitle:自定义文件名
          ids.value = []
        })
      })
      .catch((res) => {
        alert('文件压缩失败')
      })
  }

  const getImgArrayBuffer = (url: string) => {
    return new Promise((resolve, reject) => {
      //通过请求获取文件blob格式
      let xmlhttp = new XMLHttpRequest()
      xmlhttp.open('GET', url, true)
      xmlhttp.responseType = 'blob'
      xmlhttp.onload = function () {
        if (xmlhttp.status == 200) {
          resolve(xmlhttp.response)
        } else {
          reject(xmlhttp.response)
        }
      }
      xmlhttp.send()
    })
  }

  onMounted(() => {
    getList()
  })
</script>

<style lang="less" scoped>
  .download-con {
    height: calc(100vh - @menuHeight);
    // background-color: white;
  }
</style>
